package cfengMiddleware.server.controller;

import CfengMiddleWare.api.enums.StatusCode;
import CfengMiddleWare.api.response.BaseResponse;
import cfengMiddleware.server.dto.RedPackageDto;
import cfengMiddleware.server.service.RedService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * @author Cfeng
 * @date 2022/9/13
 * 发红包处理器
 */

@RestController
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/redPackage")
public class RedPackageController {

    private final RedService redPackageService;

    /**
     * 发红包的处理器，需要进行参数验证@Validate
     * 参数校验的结果由BindingResult封装接收
     * @param redPackageDto
     * @param result
     * @return
     */
    @PostMapping("/handOut")
    public BaseResponse<String> handout(@Validated @RequestBody RedPackageDto redPackageDto, BindingResult result) {
        //参数校验失败，错误的参数
        if(result.hasErrors()) {
            return new BaseResponse<>(StatusCode.INVALID_PARAMS,null,"参数校验失败,请正确输入");
        }
        try {
            //返回一个红包标识唯一字符串
            String redId = redPackageService.handOut(redPackageDto);
            //返回前端
            return BaseResponse.ok(redId);
        } catch (Exception e) {
            //发生错误
            return BaseResponse.failed("出错了" + e.getMessage().toString());
        }
    }

    @GetMapping("/rob")
    public BaseResponse<BigDecimal> rob(@RequestParam Integer userId, @RequestParam String redId) {
        try {
            //调用红包业务逻辑，返回抢到的红包金额，单位为元
            BigDecimal result = redPackageService.rob(userId,redId);
            if(!Objects.isNull(result)) {
                //抢到红包返回结果
                return BaseResponse.ok(result);
            } else {
                //红包抢光了
                return BaseResponse.failed("红包被抢光了");
            }
        } catch (Exception e) {
            log.error("抢红包发生异常, 红包ID:{},UserID:{},异常信息：{}",redId,userId,e.getMessage());
            return BaseResponse.failed("出错了" + e.getMessage());
        }
    }

}
